<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class MenuDish extends Model
{
    use HasFactory;

    protected $fillable = [
        'menu_id',
        'dish_id',
        'name',
        'description',
        'category_id',
        'image',
        'tags',
        'flavors',
        'cooking_time',
        'price',
        'is_available',
        'is_featured',
        'sort_order',
        'dish_type',
    ];

    protected $casts = [
        'tags' => 'array',
        'flavors' => 'array',
        'is_available' => 'boolean',
        'is_featured' => 'boolean',
        'price' => 'decimal:2',
    ];

    /**
     * 准备日期用于数组/JSON序列化
     */
    protected function serializeDate(\DateTimeInterface $date): string
    {
        return $date->format('Y-m-d H:i:s');
    }

    /**
     * 关联菜单
     */
    public function menu(): BelongsTo
    {
        return $this->belongsTo(Menu::class);
    }

    /**
     * 关联原始菜品
     */
    public function originalDish(): BelongsTo
    {
        return $this->belongsTo(Dish::class, 'dish_id');
    }

    /**
     * 关联分类
     */
    public function category(): BelongsTo
    {
        return $this->belongsTo(Category::class);
    }

    /**
     * 作用域：可用菜品
     */
    public function scopeAvailable($query)
    {
        return $query->where('is_available', true);
    }

    /**
     * 作用域：推荐菜品
     */
    public function scopeFeatured($query)
    {
        return $query->where('is_featured', true);
    }

    /**
     * 作用域：系统菜品
     */
    public function scopeSystem($query)
    {
        return $query->where('dish_type', 'system');
    }

    /**
     * 作用域：自定义菜品
     */
    public function scopeCustom($query)
    {
        return $query->where('dish_type', 'custom');
    }

    /**
     * 作用域：按分类
     */
    public function scopeByCategory($query, int $categoryId)
    {
        return $query->where('category_id', $categoryId);
    }

    /**
     * 作用域：按排序
     */
    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order')->orderBy('created_at');
    }

    /**
     * 搜索菜品
     */
    public function scopeSearch($query, string $keyword)
    {
        return $query->where(function ($q) use ($keyword) {
            $q->where('name', 'like', "%{$keyword}%")
              ->orWhere('description', 'like', "%{$keyword}%")
              ->orWhereJsonContains('tags', $keyword);
        });
    }
}